package com.zhangzy.qm.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.zhangzy.qm.dao.AblumDao;
import com.zhangzy.qm.dao.OptionDao;
import com.zhangzy.qm.dao.TopicDao;
import com.zhangzy.qm.dao.UserTokenDao;
import com.zhangzy.qm.entity.Ablum;
import com.zhangzy.qm.entity.Option;
import com.zhangzy.qm.entity.Topic;
import com.zhangzy.qm.entity.UserToken;
import com.zhangzy.qm.util.ApnsSend;
import com.zhangzy.qm.util.Constants;
import com.zhangzy.qm.util.FileUtil;
import com.zhangzy.qm.util.HttpUtil;
import com.zhangzy.qm.util.ImageUtil;
import com.zhangzy.qm.util.ZipUtil;

public class AblumController {

	private HttpServletRequest request = ServletActionContext.getRequest();
	private HttpServletResponse response = ServletActionContext.getResponse();
	private static final Logger logger = Logger.getLogger("ulog");
	private TopicDao topicDao;
	private AblumDao ablumDao;
	private OptionDao optionDao;
	private UserTokenDao userTokenDao;
	private File uploadify;	 
	private String uploadifyFileName;
	

	
	public UserTokenDao getUserTokenDao() {
		return userTokenDao;
	}
	public void setUserTokenDao(UserTokenDao userTokenDao) {
		this.userTokenDao = userTokenDao;
	}
	public TopicDao getTopicDao() {
		return topicDao;
	}
	public void setTopicDao(TopicDao topicDao) {
		this.topicDao = topicDao;
	}
	public OptionDao getOptionDao() {
		return optionDao;
	}
	public void setOptionDao(OptionDao optionDao) {
		this.optionDao = optionDao;
	}
	public AblumDao getAblumDao() {
		return ablumDao;
	}
	public void setAblumDao(AblumDao ablumDao) {
		this.ablumDao = ablumDao;
	}
	public File getUploadify() {
		return uploadify;
	}
	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}
	public String getUploadifyFileName() {
		return uploadifyFileName;
	}
	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}
	
	public String toAddAblu(){
		return "addAblu";
	}
	
	public String ablumIndex() throws Exception{		
		Map<String,String> params = new HashMap<String,String>();
		String title = HttpUtil.getString(request, "title","");
		String beginDate = HttpUtil.getString(request, "beginDate","");
		String endDate = HttpUtil.getString(request, "endDate","");
		int pageNum = HttpUtil.getInt(request, "page", 1);
		int pageSize = HttpUtil.getInt(request, "pageSize", 20);		
		int start = pageSize * (pageNum - 1);			
		StringBuilder sql1 = new StringBuilder();
		StringBuilder sql2 = new StringBuilder();
		sql1.append("from Ablum as a where 1=1 ");
		sql2.append("select count(*) from Ablum as a where 1=1 ");		
		if(!"".equals(title)){
			sql1.append("and a.title like '%"+title+"%' ");
			sql2.append("and a.title like '%"+title+"%' ");
		}
		if(!"".equals(beginDate) && !"".equals(endDate)){
			sql1.append("and a.saveTime BETWEEN '"+beginDate+"' and '"+endDate+"'  ");
			sql2.append("and a.saveTime BETWEEN '"+beginDate+"' and '"+endDate+"'  ");

		}
		sql1.append(" and a.state<>3 order by a.id desc");
		sql2.append(" and a.state<>3");
		List<Ablum> dataList = ablumDao.query(sql1.toString(),start,pageSize);
		int count = ablumDao.queryCount(sql2.toString());
		params.put("title", title);
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		request.setAttribute("dataList", dataList);
		request.setAttribute("params", params);
		request.setAttribute("count", count);
		request.setAttribute("pageCount", (count - 1) / pageSize + 1);
		request.setAttribute("pageNum", pageNum);		
		request.setAttribute("pageSize", pageSize);		
		return "ablumIndex";
	}
	
	
	public void imageDisplay(){
		String imageUrl = HttpUtil.getString(request, "imageUrl","");
		if(imageUrl!=null && !"".equals(imageUrl) ){
			ImageUtil.base64StringToImage(ImageUtil.getImageBinary(imageUrl),response);
		}
	}
	/**
	 * 添加专辑
	 * @Methods Name addAblb
	 * @Create In Apr 30, 2012 By zhenyu
	 * @return String
	 * @throws IOException 
	 */
	public void doAddAblu() throws IOException{
		String imageUrl = HttpUtil.getString(request, "imageUrl","");
		String title = HttpUtil.getString(request, "title","");
		String remark = HttpUtil.getString(request, "remark","");
		int type = HttpUtil.getInt(request, "type",0);
		int isFree =HttpUtil.getInt(request, "isFree" , 1);//1:免费 2：收费
		float value = HttpUtil.getFloat(request, "value",0);//收费金额
		String iapid = HttpUtil.getString(request, "iapid","");//产品id
		Ablum ablum = new Ablum();
		ablum.setTitle(title);
		ablum.setRemark(remark);
		ablum.setImageUrl(imageUrl);
		ablum.setType(type);
		ablum.setState(1);//未完成
		ablum.setSaveTime(new Date());
		ablum.setIsFree(isFree);
		ablum.setValue(value);
		ablum.setIapid(iapid);
		ablumDao.save(ablum);
//		try {
//			generateZipFile(ablum.getId());//生成zip包
//		} catch (Exception e) {
//			logger.error(e.getMessage());
//		}
		response.sendRedirect(request.getContextPath()+"/ablumIndex.action");
	}
	
	/**
	 * 上传专辑封面
	 * @Methods Name doUpload
	 * @Create In Apr 30, 2012 By zhenyu
	 * @throws Exception void
	 */
	public void doUpload() throws Exception{
		  String extName = "";//扩展名		  
		  String newFileName= "";//新文件名		  
		  String nowTime = new SimpleDateFormat("yyyymmddHHmmss").format(new Date());//当前时间		  
		  //String savePath =ServletActionContext.getServletContext().getRealPath(""); //获取项目根路径
		  String savePath =Constants.uploadPath;
		  File f = new File(savePath);
		  if(!(f.exists())){
			  f.mkdirs();
		  }
		  HttpServletResponse response = ServletActionContext.getResponse();
		  response.setCharacterEncoding("utf-8");
		  
		  //获取扩展名
		  if(uploadifyFileName.lastIndexOf(".")>=0){
		   extName = uploadifyFileName.substring(uploadifyFileName.lastIndexOf("."));
		  }
		  newFileName = nowTime+extName;
		  System.out.println("==========savePath+newFileName:"+savePath+newFileName);
		  uploadify.renameTo(new File(savePath+newFileName)); //文件上传后重命名
//		  uploadify.renameTo(new File(savePath+uploadifyFileName));//文件上传后，还为原来的名称		
		  response.getWriter().print(savePath+newFileName);	
	}
	public String toUpdateAblum(){
		int id = HttpUtil.getInt(request, "id",0);
		Ablum ab = ablumDao.getAblum(id);
		request.setAttribute("ab", ab);
		return "updateAblum";
	}
	public void doUpdateAblum() throws IOException{
		int id = HttpUtil.getInt(request, "id",0);
		String imageUrl = HttpUtil.getString(request, "imageUrl","");
		String title = HttpUtil.getString(request, "title","");
		String remark = HttpUtil.getString(request, "remark","");
		int type = HttpUtil.getInt(request, "type",0);
		int state = HttpUtil.getInt(request, "state",0);
		int isFree =HttpUtil.getInt(request, "isFree" , 1);//1:免费 2：收费
		float value = HttpUtil.getFloat(request, "value",0);//收费金额	
		String iapid = HttpUtil.getString(request, "iapid","");//产品id
		if(id!= 0 && !"".equals(title)){
			Ablum ab = ablumDao.getAblum(id);
			ab.setTitle(title);
			ab.setRemark(remark);
			ab.setType(type);
			ab.setState(state);
			ab.setIsFree(isFree);
			ab.setValue(value);
			ab.setImageUrl(imageUrl);
			ab.setIapid(iapid);
			ablumDao.update(ab);
			try {
				generateZipFile(id);//生成zip包
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		response.sendRedirect(request.getContextPath()+"/ablumIndex.action");
	}
	
	public void removeAblum() throws IOException{
		int id = HttpUtil.getInt(request, "id",0);
		if(id!=0){
			Ablum ab = ablumDao.getAblum(id);
			ab.setId(id);
			ab.setState(3);
			ablumDao.update(ab);
			removeFile(id);//删除专辑zip
		}		
		response.sendRedirect(request.getContextPath()+"/ablumIndex.action");

	}
	
	/**
	 * 生成zip文件
	 * @Methods Name generateZipFile
	 * @Create In Jul 15, 2012 By zhenyu
	 * @param topicId
	 * @return
	 * @throws Exception boolean
	 */
	private boolean generateZipFile(int subjectId) throws Exception{
		List<Topic> topicList = new ArrayList<Topic> ();
		try {
			if(subjectId!=0){
				removeFile(subjectId);//删除zip包
				String zipPath=Constants.zipPath+"/"+subjectId+"/"+subjectId+"/";//需要打包的专辑资源存放位置
				String zipSrcPath=zipPath+"/src/";//需要打包的专辑资源存放位置
				File f1 = new File(zipPath);
				if(!(f1.exists())){
					f1.mkdirs();
				}
				File f2 = new File(zipSrcPath);
				if(!(f2.exists())){
					f2.mkdirs();
				}
				Ablum ab = ablumDao.getAblum(subjectId);	
				String image="";
				if(ab.getImageUrl()!=null && !"".equals(ab.getImageUrl())){
					String urlValue = ab.getImageUrl();
					//初始化的图片的在特殊的文件里，要把路径替换掉
					if(urlValue.contains(Constants.uploadPath+"10001/") || urlValue.contains(Constants.uploadPath+"10002/") 
						|| urlValue.contains(Constants.uploadPath+"10003/") ||urlValue.contains(Constants.uploadPath+"10004/")
						|| urlValue.contains(Constants.uploadPath+"10005/") || urlValue.contains(Constants.uploadPath+"10006/")){
						urlValue = urlValue.replaceAll("10001/", "");
						urlValue = urlValue.replaceAll("10002/", "");
						urlValue = urlValue.replaceAll("10003/", "");
						urlValue = urlValue.replaceAll("10004/", "");
						urlValue = urlValue.replaceAll("10005/", "");
						urlValue = urlValue.replaceAll("10006/", "");
					}
					image = urlValue.replace(Constants.uploadPath, "src/");
					
					
					FileUtil.copy(ab.getImageUrl() , zipPath+image);//复制专辑封面
				}
				StringBuilder sb = new StringBuilder("{");
				sb.append("\"subjectId\":\""+ab.getId()+"\" , ");
				sb.append("\"subjectName\":\""+formatString(ab.getTitle())+"\" , ");
				sb.append("\"subjectType\":\"0"+ab.getType()+"\" , ");
				sb.append("\"subjectImage\":\""+image+"\" , ");
				sb.append("\"subjectInfo\":\""+formatString(ab.getRemark())+"\" , ");
				sb.append("\"paperList\":[");
				
				//免费版下载数据只提供学院类<=5年级，明星类<=3
				topicList = topicDao.query(" from Topic t where t.ablum.id="+ab.getId()
						+" and ((t.gradeType=1 and t.gradeId<=5) or (t.gradeType!=1 and t.gradeId<=3))");
				Collections.shuffle(topicList); //打乱顺序
				int j =0;
				for(Topic topic:topicList){
					String qContent ="";
					if(topic.getType()==1){
						qContent=topic.getTitle();
					}else{
						qContent=topic.getResourceUrl();
						//初始化的图片的在特殊的文件里，要把路径替换掉
						if(qContent.contains(Constants.uploadPath+"10001/") || qContent.contains(Constants.uploadPath+"10002/") 
							|| qContent.contains(Constants.uploadPath+"10003/") ||qContent.contains(Constants.uploadPath+"10004/")
							|| qContent.contains(Constants.uploadPath+"10005/") || qContent.contains(Constants.uploadPath+"10006/")){
							qContent = qContent.replaceAll("10001/", "");
							qContent = qContent.replaceAll("10002/", "");
							qContent = qContent.replaceAll("10003/", "");
							qContent = qContent.replaceAll("10004/", "");
							qContent = qContent.replaceAll("10005/", "");
							qContent = qContent.replaceAll("10006/", "");
						}
						qContent = qContent.replace(Constants.uploadPath,"src/");
						FileUtil.copy(topic.getResourceUrl() , zipPath+qContent);//复制资源文件 
					}
					String subjectInfo = topic.getRemark();
					subjectInfo = formatString(subjectInfo);
					List<Option> optionList = optionDao.query("from Option o where o.topic.id="+topic.getId());
					List<Option> resultList = new ArrayList<Option>();
					if(optionList!=null && (optionList.size()==2 || optionList.size()>=4)){//只有满足此条件才打包
						if(j!=0){
							sb.append(" , ");
						}
						sb.append("{");
						sb.append("\"questionId\":\""+topic.getId()+"\" , ");
						sb.append("\"questionType\":\"0"+topic.getType()+"\" , ");
						sb.append("\"subjectId\":\""+topic.getAblum().getId()+"\" , ");
						sb.append("\"questionContent\":\""+qContent+"\" , ");
						sb.append("\"subjectInfo\":\""+subjectInfo+"\" , ");
						sb.append("\"grade\":\""+topic.getGradeId()+"\" , ");
						for(Option option:optionList){
							if(option.getRightFlag()==1){
								resultList.add(option);
								optionList.remove(option);//此处删除是为了下面的逻辑随机取值时都取的为不正确的结果
								break;
							}
						}
						Collections.shuffle(optionList); //打乱顺序
						if(optionList.size()>0){
							resultList.add(optionList.get(0));
						}
						if(optionList.size()>1){
							resultList.add(optionList.get(1));
						}
						if(optionList.size()>2){
							resultList.add(optionList.get(2));
						}	
						if(resultList.size()==1){
							Option o1 = new Option();
							o1.setTitle("");
							Option o2 = new Option();
							o2.setTitle("");
							Option o3 = new Option();
							o3.setTitle("");
							resultList.add(o1);
							resultList.add(o2);
							resultList.add(o3);
						}else if(resultList.size()==3){
							Option o1 = new Option();
							o1.setTitle("");
							resultList.add(o1);
						}else if(resultList.size()==0){
							Option o1 = new Option();
							o1.setTitle("");
							Option o2 = new Option();
							o2.setTitle("");
							Option o3 = new Option();
							o3.setTitle("");
							Option o4 = new Option();
							o4.setTitle("");
							resultList.add(o1);
							resultList.add(o2);
							resultList.add(o3);
							resultList.add(o4);
						}
						Collections.shuffle(resultList); //打乱顺序 
						int i = 0;
						boolean tempFlag = false;
						for(Option option:resultList){
							String optionFlag = "option";
							if(i==0){
								optionFlag="A";
							}else if(i==1){
								optionFlag="B";
							}else if(i==2){
								optionFlag="C";
							}else if(i==3){
								optionFlag="D";
							}
							if(option.getRightFlag()==1){
								tempFlag=true;
								sb.append("\"option"+optionFlag+"\":\""+formatString(option.getTitle())+"\" , ");	
								sb.append("\"correctAnswer\":\""+optionFlag+"\" ");						
							}else{
								sb.append("\"option"+optionFlag+"\":\""+formatString(option.getTitle())+"\" ");				
							}
							if(i!=resultList.size()-1){
								sb.append(",");
							}					
							i++;
						}
						if(!tempFlag){//没有正确答案，默认A
							sb.append(",\"correctAnswer\":\"A\" ");		
						}
						if(resultList.size()==2){//只有两个选项，c,d 设置为空
							sb.append(",\"optionC\":\"\",\"optionD\":\"\"");	
						}				
						j++;
						sb.append("}");
					}				
			}
			sb.append("]");
			sb.append("}");	  
			FileUtil.writeFile(sb.toString(),zipPath+subjectId+".txt");//写json文件	
			ZipUtil.zip(Constants.zipPath+"/"+subjectId, Constants.zipPath+"/"+subjectId+".zip");				
			}
		} catch (Exception e) {
			logger.error("gen zip",e);
			return false;
		}
		FileUtil.deletefile(Constants.zipPath+"/"+subjectId);
		return true;
	}
	
	private void removeFile(int subjectId){
		if(subjectId!=0){
			try {
				logger.info("remove file:"+subjectId+".zip");
				FileUtil.deletefile(Constants.zipPath+"/"+subjectId+".zip");
				FileUtil.deletefile(Constants.zipPath+"/"+subjectId);
			} catch (FileNotFoundException e) {
				System.out.println(e.getStackTrace());
			} catch (IOException e) {
				logger.error(e.getStackTrace());
			}
		}		
	}
	
	public static String formatString(String str) {
		// 过滤掉特殊字符
		str = str.replaceAll("\r", "").replaceAll("\t", "").replaceAll("\n", "");	
		str = str.trim();
		return str;
	}
	
	/**
	 * 推送功能首页
	 * @Methods Name pushDataIndex
	 * @Create In Sep 15, 2012 By zhenyu
	 * @return
	 * @throws Exception String
	 */
	public String pushDataIndex() throws Exception{
		Map<String,String> params = new HashMap<String,String>();
		String title = HttpUtil.getString(request, "title","");
		int pageNum = HttpUtil.getInt(request, "page", 1);
		int pageSize = HttpUtil.getInt(request, "pageSize", 20);		
		int start = pageSize * (pageNum - 1);			
		StringBuilder sql1 = new StringBuilder();
		StringBuilder sql2 = new StringBuilder();
		sql1.append("from Ablum as a where 1=1 ");
		sql2.append("select count(*) from Ablum as a where 1=1 ");		
		if(!"".equals(title)){
			sql1.append("and a.title like '%"+title+"%' ");
			sql2.append("and a.title like '%"+title+"%' ");
		}
		
		sql1.append(" and a.state=2 order by a.id desc");
		sql2.append(" and a.state=2 ");
		List<Ablum> dataList = ablumDao.query(sql1.toString(),start,pageSize);
		int count = ablumDao.queryCount(sql2.toString());
		params.put("title", title);
		request.setAttribute("dataList", dataList);
		request.setAttribute("params", params);
		request.setAttribute("count", count);
		request.setAttribute("pageCount", (count - 1) / pageSize + 1);
		request.setAttribute("pageNum", pageNum);		
		request.setAttribute("pageSize", pageSize);	
		return "pushDataIndex";
	}
	
	
	public void doPushData() throws Exception{
		String ids = HttpUtil.getString(request, "ids","");
		String alertMessage = HttpUtil.getString(request, "alertMessage","有新试题可以更新");
		String[] idArray = null;
		boolean flag = true;
		String errorMessage="";
		if(!"".equals(ids)){
			idArray = ids.split(",");
		}
		
		for(String subjectId:idArray){
			String path = Constants.zipPath+"/"+subjectId+".zip";
			FileUtil.deletefile(Constants.zipPath+"/"+subjectId);//删除文件夹里的冗余数据
			File file = new File(path);
			if (!file.exists()) {//检查压缩包是否存在
				Ablum ab = (Ablum) ablumDao.getObjectById(Ablum.class, Integer.valueOf(subjectId));
				flag = false;
				errorMessage="专辑："+ab.getTitle()+" 没有压缩包，请重新生成！";
				break;
			}
		}
		if(flag){
			int badge = idArray.length;//更新数量
			//String alertMessage = "有新试题可以更新";
			List<UserToken> list = (List<UserToken>)userTokenDao.getObjects(UserToken.class);
			for(UserToken token :list){
				logger.info("token:"+token.getUserToken()+" , alertMessage:"+alertMessage+" , badge:"+badge);
				ApnsSend.doSend(token.getUserToken(), alertMessage, badge);
			}
			
		}
		JSONObject json = new JSONObject();
		json.put("success", flag);
		json.put("errorMessage", errorMessage);
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;		
		try{
			out = response.getWriter();
			out.println(json.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			logger.error("doPushData",e);
		}
		
	}

}
